package pers.hl.lib_global.http

import com.blankj.utilcode.util.LogUtils
import com.tencent.mmkv.MMKV
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import pers.hl.common.http.BaseInterceptor
import pers.hl.lib_global.common.Const

/**
 * 认证请求拦截器，统一添加token认证
 */
class AuthInterceptor: BaseInterceptor() {

    var WHITE_LIST : List<String> = listOf("login", "sign_up", "douban")

    override fun needIntercept(request: Request): Boolean {
        request.apply {
            val originUrl = url.toString()
            for (url in WHITE_LIST) {
                if (originUrl.contains(url)) {
                    LogUtils.d("need not intercept:$originUrl")
                    return false
                }
                LogUtils.d("need intercept:$originUrl")
            }
        }
        return true
    }

    override fun doIntercept(chain: Interceptor.Chain, request: Request): Response {
        val token = MMKV.defaultMMKV()?.decodeString(Const.KEY.KEY_TOKEN)
        val builder = request.newBuilder()
        token?.let {
            builder.addHeader(Const.KEY.KEY_AUTHORIZATION, it)
//            LogUtils.dTag(TAG, "添加了认证token：$token")
            return chain.proceed(builder.build())
        }
        return chain.proceed(request)
    }

}